package market

import (
	"go_server/game_server/api/service/bag"
	"go_server/game_server/dao/daily_dao"
	"go_server/game_server/dataconfig/config_manager"
	"go_server/game_server/protocol/pb"
	"go_server/game_server/util"
	"go_server/game_server/world_manager"
	"go_server/zinx/ziface"
	"go_server/zinx/zlog"
	"go_server/zinx/znet"
	"gorm.io/datatypes"
	"math"
	"time"
)

type MarketExchangeApi struct {
	znet.BaseRouter
}

// 商店兑换
func (*MarketExchangeApi) Handle(request ziface.IRequest) {
	msg := &pb.MarketExchangeC2S{}
	if !util.PBParseRet(request, msg) {
		return
	}

	conn := request.GetConnection()
	roleId := ServiceObj.GetRoleId(request)

	// 获取商店商品配置
	baseItemInfo, ok := config_manager.GetStcTableShop_SheetShopById(msg.ItemId)
	if !ok {
		world_manager.WorldMgrObj.SendClientErrMsg(roleId, request, pb.ErrorCodeManager_SHOP_CONFIG_NOT_FIND, nil)
		return
	}

	limitBuyTimes := baseItemInfo.Buynumber // 限购次数
	discount := baseItemInfo.Discount       // 折扣
	price := baseItemInfo.Price             // 购买消耗
	spendItemId := price[0]                 // 消耗的物品id
	spendNum := price[1]                    // 消耗的数量

	if discount > 0 && spendNum > 0 {
		// 向上取整
		spendNum = int32(math.Ceil(float64(spendNum) * float64(discount)))
	}

	if !bag.CheckItemEnough(roleId, spendItemId, spendNum) { // 资源道具不足
		world_manager.WorldMgrObj.SendClientErrMsg(roleId, request, pb.ErrorCodeManager_SPEND_ITEM_NOT_ENOUGH, nil)
		return
	}

	// 获取本周的第一天（周一）
	weekStartKey := time.Now().AddDate(0, 0, -int(time.Now().Weekday())+1).Format("20060102")
	fields := []string{"market_item_info"}
	row := daily_dao.GetDailyByDateKey(weekStartKey, roleId, fields)

	marketItemInfo := make(map[int32]int32)

	if row != nil && row.MarketItemInfo.Data() != nil {
		marketItemInfo = row.MarketItemInfo.Data()
	}

	useTime, exist := marketItemInfo[msg.ItemId]
	if exist {
		if limitBuyTimes > 0 && useTime >= limitBuyTimes { // 已超出限购次数
			world_manager.WorldMgrObj.SendClientErrMsg(roleId, request, pb.ErrorCodeManager_UP_LEVEL_LIMIT_BUY_TIMES, nil)
			return
		}

		useTime += 1
	} else {
		useTime = 1
	}

	marketItemInfo[msg.ItemId] = useTime
	remainTime := limitBuyTimes - useTime // 剩余次数

	res := &pb.MarketExchangeS2C{
		ItemId:     msg.ItemId,
		RemainTime: remainTime,
	}

	zlog.Infof("res=%v", res)
	conn.SendBuffPBMsg(uint32(pb.ProtocolManager_marketExchange), res)

	// 修改任务状态
	dailyObj := daily_dao.Daily{
		DateKey:        weekStartKey,
		RoleId:         roleId,
		MarketItemInfo: datatypes.NewJSONType(marketItemInfo),
	}
	daily_dao.UpdateDailyByDateKey(&dailyObj, fields)

	// 扣除消耗资源,发送奖励
	bag.SubItemSingle(roleId, spendItemId, spendNum)
	bag.AddItemSingle(roleId, baseItemInfo.Itemid, baseItemInfo.Number)
}
